package com.campus.counseling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.campus.counseling.entity.ConsultationRecord;
import com.campus.counseling.entity.AIChatSession;
import com.campus.counseling.entity.Counselor;
import com.campus.counseling.model.mapper.*;
import com.campus.counseling.model.vo.ProblemTypeStatsVO;
import com.campus.counseling.model.vo.CounselorIncomeVO;
import com.campus.counseling.service.AnalysisService;
import com.campus.counseling.entity.Appointment;
import com.campus.counseling.entity.PaymentRecord;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AnalysisServiceImpl implements AnalysisService {

    private final ConsultationRecordMapper consultationRecordMapper;
    private final AIChatSessionMapper aiChatSessionMapper;
    private final CounselorMapper counselorMapper;
    private final AppointmentMapper appointmentMapper;
    private final PaymentRecordMapper paymentRecordMapper;

    @Override
    public Map<String, Object> getConsultationTypeStats(String timeRange) {
        LocalDateTime startTime = getStartTime(timeRange);
        
        // 查询普通咨询记录数量（从consultation_record表中查询）
        Long normalCount = consultationRecordMapper.selectCount(
            new LambdaQueryWrapper<ConsultationRecord>()
                .ge(startTime != null, ConsultationRecord::getConsultationTime, startTime)
                .eq(ConsultationRecord::getDeleted, 0)
        );
        
        // 查询AI咨询会话数量
        Long aiCount = aiChatSessionMapper.selectCount(
            new LambdaQueryWrapper<AIChatSession>()
                .ge(startTime != null, AIChatSession::getCreateTime, startTime)
        );
        
        // 计算环比增长
        LocalDateTime lastStartTime = startTime != null ? 
            startTime.minusDays(getDaysFromTimeRange(timeRange)) : null;
            
        // 查询上期普通咨询记录数量
        Long lastNormalCount = consultationRecordMapper.selectCount(
            new LambdaQueryWrapper<ConsultationRecord>()
                .ge(lastStartTime != null, ConsultationRecord::getConsultationTime, lastStartTime)
                .lt(startTime != null, ConsultationRecord::getConsultationTime, startTime)
                .eq(ConsultationRecord::getDeleted, 0)
        );
        
        // 查询上期AI咨询会话数量
        Long lastAiCount = aiChatSessionMapper.selectCount(
            new LambdaQueryWrapper<AIChatSession>()
                .ge(lastStartTime != null, AIChatSession::getCreateTime, lastStartTime)
                .lt(startTime != null, AIChatSession::getCreateTime, startTime)
        );
        
        // 计算增长率
        double aiGrowth = lastAiCount == 0 ? 100.0 : 
            (aiCount - lastAiCount) * 100.0 / lastAiCount;
        double normalGrowth = lastNormalCount == 0 ? 100.0 : 
            (normalCount - lastNormalCount) * 100.0 / lastNormalCount;
        
        Map<String, Object> result = new HashMap<>();
        result.put("aiCount", aiCount);
        result.put("normalCount", normalCount);
        result.put("aiGrowth", aiGrowth);
        result.put("normalGrowth", normalGrowth);
        
        return result;
    }

    @Override
    public ProblemTypeStatsVO getProblemTypeDistribution(String timeRange) {
        LocalDateTime startTime = getStartTime(timeRange);
        
        // 定义问题类型映射
        Map<String, String> typeMap = new HashMap<>();
        typeMap.put("PERSONAL", "个人成长");
        typeMap.put("ACADEMIC", "学业问题");
        typeMap.put("EMOTIONAL", "情感困扰");
        typeMap.put("OTHER", "其他");
        
        // 查询时间范围内的所有预约记录
        List<Appointment> appointments = appointmentMapper.selectList(
            new LambdaQueryWrapper<Appointment>()
                .ge(startTime != null, Appointment::getAppointmentTime, startTime)
                .eq(Appointment::getDeleted, 0)
                .isNotNull(Appointment::getType)
        );
        
        // 统计各问题类型的数量
        Map<String, Long> typeCountMap = appointments.stream()
            .collect(Collectors.groupingBy(
                appointment -> typeMap.getOrDefault(appointment.getType(), "其他"),
                Collectors.counting()
            ));
        
        // 计算百分比并构建返回对象
        ProblemTypeStatsVO result = new ProblemTypeStatsVO();
        result.setTotal(appointments.size());
        
        List<ProblemTypeStatsVO.TypeDistribution> distribution = typeCountMap.entrySet().stream()
            .map(entry -> {
                ProblemTypeStatsVO.TypeDistribution td = new ProblemTypeStatsVO.TypeDistribution();
                td.setType(entry.getKey());  // 这里已经是中文类型了
                td.setCount(entry.getValue().intValue());
                double percentage = appointments.size() > 0 ? 
                    (entry.getValue() * 100.0) / appointments.size() : 0.0;
                td.setPercentage(percentage);
                return td;
            })
            .collect(Collectors.toList());
        
        result.setDistribution(distribution);
        return result;
    }

    @Override
    public List<CounselorIncomeVO> getCounselorIncome(String month, String timeRange) {
        // 查询所有咨询师
        List<Counselor> counselors = counselorMapper.selectList(
            new LambdaQueryWrapper<Counselor>()
                .eq(Counselor::getStatus, "APPROVED")
        );
        
        // 查询每个咨询师的收入数据
        return counselors.stream().map(counselor -> {
            CounselorIncomeVO vo = new CounselorIncomeVO();
            vo.setCounselorId(counselor.getId().toString());
            vo.setCounselorName(counselor.getRealName());
            vo.setRating(counselor.getRating());
            
            // 查询支付记录，只过滤支付成功的记录
            List<PaymentRecord> payments = paymentRecordMapper.selectList(
                new LambdaQueryWrapper<PaymentRecord>()
                    .eq(PaymentRecord::getCounselorId, counselor.getId())
                    .eq(PaymentRecord::getPaymentStatus, "SUCCESS")
                    .eq(PaymentRecord::getDeleted, 0)
                    .ne(PaymentRecord::getPaymentStatus, "REFUNDED")
            );
            
            // 计算总收入
            BigDecimal totalIncome = payments.stream()
                .map(PaymentRecord::getCounselorAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            // 设置统计数据
            vo.setAppointmentCount(payments.size());
            vo.setIncome(totalIncome);
            vo.setCompletionRate(100.0); // 默认完成率为100%
            
            return vo;
        }).collect(Collectors.toList());
    }
    
    private LocalDateTime getStartTime(String timeRange) {
        if (timeRange == null) {
            return null;
        }
        
        LocalDateTime now = LocalDateTime.now();
        return switch (timeRange.toLowerCase()) {
            case "week" -> now.minusDays(7);
            case "month" -> now.minusDays(30);
            case "year" -> now.minusDays(365);
            default -> null;
        };
    }
    
    private int getDaysFromTimeRange(String timeRange) {
        return switch (timeRange.toLowerCase()) {
            case "week" -> 7;
            case "month" -> 30;
            case "year" -> 365;
            default -> 7;
        };
    }
    
    private BigDecimal calculateIncome(List<ConsultationRecord> records) {
        // 由于ConsultationRecord没有fee字段，暂时返回0
        return BigDecimal.ZERO;
    }
    
    private Double calculateCompletionRate(List<PaymentRecord> payments) {
        if (payments.isEmpty()) {
            return 0.0;
        }
        long completedCount = payments.stream()
            .filter(p -> p.getDistributionStatus() != null && p.getDistributionStatus().equals("DISTRIBUTED"))
            .count();
        return Double.valueOf(completedCount * 100.0 / payments.size());
    }
} 